<template>
  <div class="commodity">
    <div class="common">
      <div class="header">
        <div class="list" v-for="(item, index) in 2" :key="index" :class="{ active: index == headerIndex }"
          @click="headerHit(index)">
          {{ index == 0 ? "上架" : "下架" }}
        </div>
      </div>
    </div>
    <div class="search">
      <div class="input">
        <el-input v-model="commonValue" placeholder="商品名称" clearable></el-input>
      </div>
      <div class="input">
        <el-cascader v-model="commonCascaderValue" :options="commonCascaderOptions" :props="propsCascader" clearable
          @expand-change="commonCascaderChange"></el-cascader>
      </div>

      <div class="common-button" @click="searchHit">搜索</div>
      <div class="common-button" style="background: #999999" @click="replacementHit">
        重置
      </div>

      <div class="common-button" v-if="headerIndex == 1" @click="addHit" style="background: #2a82e4">
        新增商品
      </div>
    </div>

    <div class="table" v-loading="loading">
      <el-table :data="tableData" style="width: 100%" @sort-change="sortChange" border :header-cell-style="{
        color: '#333333',
        backgroundColor: '#f3f3f3',
      }">
        <el-table-column prop="goodName" label="商品名称" width="300">
        </el-table-column>
        <el-table-column prop="" label="商品图">
          <template slot-scope="scope">
            <img class="imgs" :src="scope.row.goodIcon" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="goodOneClassifyName" label="商品分类">
        </el-table-column>
        <el-table-column prop="retailPrice" label="销售价（元）" sortable>
        </el-table-column>
        <el-table-column prop="costPrice" label="成交价" sortable>
        </el-table-column>
        <el-table-column prop="inventoryNum" label="库存" sortable>
        </el-table-column>
        <el-table-column prop="saleNum" label="真实销量" sortable>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <div class="operation">
              <div class="list" @click.prevent="detailsHit(scope.row)">
                详情
              </div>

              <div class="list" @click.prevent="editHit(scope.row)" v-if=" scope.row.isStatus == 0">编辑</div>


              <div class="list" @click.prevent="upHit(scope.row)">
                {{ scope.row.isStatus == 1 ? "下架" : "上架" }}
              </div>

              <div class="list" @click.prevent="evaluateHit(scope.row)">
                评价
              </div>

              <div class="list" @click.prevent="deleteHit(scope.row)" v-if=" scope.row.isStatus == 0">删除</div>

            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
          layout="prev, pager, next" :total="tableDataTotal" :current-page="page">
        </el-pagination>
      </div>
    </div>

    <!--提示弹出框-->
    <div class="delete">
      <el-dialog title="提示" :visible.sync="warningVisible" :before-close="warningClose">
        <div class="delete-title">
          是否将这个商品{{ commonObj.isStatus == 1 ? "下架" : "上架" }}？
        </div>
        <div class="delete-attachment">
          <div class="list" @click="warningClose">取消</div>
          <div class="list" @click="warningConfirm">确定</div>
        </div>
      </el-dialog>
    </div>


    <!--删除弹出框-->
    <div class="delete">
      <el-dialog title="删除" :visible.sync="deleteVisible" :before-close="deleteClose">
        <div class="delete-title">是否确认删除？</div>
        <div class="delete-attachment">
          <div class="list" @click="deleteClose">取消</div>
          <div class="list" @click="deleteConfirm">确定</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  saveCommodityClassifyList,
  saveCommodityList,
  saveCommodityListIdPut,
  saveCommodityListIdDelete
} from "@/api/save";

export default {
  data() {
    return {
      headerIndex: 0,
      commonValue: "",
      commonCascaderOptions: [],
      commonCascaderValue: "",
      propsCascader: {
        value: "goodClassifyId",
        label: "goodClassifyName",
        children: "children",
        checkStrictly: true,
      },
      commonCascaderIndex: 0,
      //-------------
      page: 1,
      limit: 10,
      tableData: [],
      tableDataTotal: 0,
      loading: false,
      commonObj: {},
      //--------------
      tabSort: 0, //该字段代表升序还是降序 假设：0正序 1倒序
      tabProp: 0, //prop绑定的字段名
      //------
      warningVisible: false,
      //-----------
      deleteVisible: false,
      deleteObj: {}
    };
  },

  created() {
    if(this.$route.query.index) {
      this.headerIndex = this.$route.query.index
    }

    this.loading = true;
    this.saveCommodityClassifyListMet();

    this.saveCommodityListMet();
  },
  methods: {
    // 加载一级数据
    saveCommodityClassifyListMet() {
      let params = {
        goodClassifyType: 0,
        fatherId: "",
        pageSize: this.limit,
        pageNo: this.page,
      };

      saveCommodityClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.goodClassifyList.forEach((item, index) => {
            item.children = [];
          });
          this.commonCascaderOptions = res.resultData.goodClassifyList;
        }
      });
    },
    commonCascaderChange(e) {
      this.loadCascaderData(e[0]);
    },
    // 动态加载级联数据
    loadCascaderData(id) {
      let params = {
        goodClassifyType: 0,
        fatherId: id,
      };

      saveCommodityClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          let mockData = res.resultData.goodClassifyList;

          this.commonCascaderOptions.forEach((item, index) => {
            if (item.goodClassifyId == id) {
              item.children = mockData;
            }
          });
        }
      });
    },

    saveCommodityListMet() {
      let params = {
        bannerId: "",
        goodName: this.commonValue,
        goodClassifyId:
          this.commonCascaderValue[this.commonCascaderValue.length - 1],
        orderType: this.tabProp, // 排序字段 0无 1销售价 2销售数量 3创建时间
        orderBy: this.tabSort, // 排序类型 0正 1倒
        isStatus: this.headerIndex == 0 ? 1 : 0,

        pageSize: this.limit,
        pageNo: this.page,
      };

      saveCommodityList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.goodList.forEach((item, index) => {
            item.retailPrice = Number(item.retailPrice / 100).toFixed(2);
            item.costPrice = Number(item.costPrice / 100).toFixed(2);
          });

          this.tableData = res.resultData.goodList;
          this.tableDataTotal = res.resultData.totalNum;
          this.loading = false;
        }
      });
    },

    searchHit() {
      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    replacementHit() {
      this.commonValue = "";
      this.commonCascaderValue = "";

      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    //------------------------------------------------
    sortChange(column) {
      // 当前列的排序  ascending 升序 descending 降序
      console.log("获取对象", column);
      if (column.order == "ascending") {
        this.tabSort = 0;
      } else if (column.order == "descending") {
        this.tabSort = 1;
      } else {
        this.tabSort = 0;
      }

      // 当前点击列名
      this.tabProp =
        column.prop == "retailPrice"
          ? 1
          : column.prop == "costPrice"
            ? 2
            : column.prop == "inventoryNum"
              ? 3
              : column.prop == "saleNum"
                ? 4
                : 0;

      this.page = 1;
      this.loading = true;
      this.saveCommodityListMet();
    },

    //------------------------------------
    headerHit(index) {
      this.headerIndex = index;
      this.page = 1;
      this.loading = true;
      this.saveCommodityListMet();
    },
    //-------------
    addHit() {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }
      this.$router.push({
        path: "/save/commodity/commodity-list-add",
        query: {
          soucre: 0,
        },
      });
    },
    editHit(item) {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }
      this.$router.push({
        path: "/save/commodity/commodity-list-add",
        query: {
          soucre: 0,
          id: item.goodId,
        },
      });
    },
    detailsHit(item) {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }
      this.$router.push({
        path: "/save/commodity/commodity-list-add",
        query: {
          soucre: 1,
          id: item.goodId,
        },
      });
    },
    //---------------------------------------------
    upHit(item) {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }
      this.commonObj = item;
      this.warningVisible = true;
    },

    warningClose() {
      this.warningVisible = false;
    },

    warningConfirm() {
      let params = this.commonObj.goodId;

      saveCommodityListIdPut(params).then((res) => {
        if (res.errorCode == null) {
          this.warningVisible = false;
          this.$message.success("状态更换成功！");
          this.loading = true;
          this.saveCommodityListMet();
        }
      });
    },
    //---------------------------------------------
    evaluateHit(item) {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }
      this.$router.push({
        path: "/save/commodity/commodity-list-evaluate",
        query: {
          id: item.goodId,
        },
      });
    },
    //---------
    deleteHit(item) {
      if (this.$store.state.premissions.infoRouterShow == false) {
        this.$message.error("暂无权限，请联系管理员开通");
        return;
      }

      this.deleteObj = item;
      this.deleteVisible = true;
    },
    deleteClose() {
      this.deleteVisible = false;
    },
    deleteConfirm() {
      let params = this.deleteObj.goodId;

      saveCommodityListIdDelete(params).then(res => {
        if (res.errorCode == null) {
          this.deleteVisible = false;
          this.$message.success("删除成功！");
          this.loading = true;
          this.saveCommodityListMet();
        }
      })

    },
    //---------

    //---------
    handleSizeChange(val) {
      this.limit = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
  },
};
</script>

<style lang="less" scoped>
@import url("@/assets/css/common.less");
@import url("@/assets/css/delete.less");

.commodity {
  .common {
    .header {
      width: 100%;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ccc;

      .list {
        width: 150px;
        height: 35px;
        background: #999999;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        cursor: pointer;
      }

      .active {
        background: #2a82e4;
      }
    }
  }

  .search {
    display: flex;
    align-items: center;

    .input {
      margin-right: 10px;

      /deep/ .el-input {
        width: 250px;
      }
    }

    .common-button {
      padding: 9px 20px;
      box-sizing: border-box;
      border-radius: 5px;
      background: #2a82e4;
      font-size: 14px;
      color: #fff;
      margin-left: 20px;
      cursor: pointer;
    }

    .common-button:last-child {
      background: #999999;
    }
  }

  .table {
    margin-top: 10px;
  }
}
</style>